package com.hqbzl.c1.rlock;

import lombok.extern.java.Log;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

@Slf4j
public class TestLock {
    static boolean r1 = false;
    static boolean r2 = false;

    public static void main(String[] args) {
        final ReentrantLock ROOM = new ReentrantLock();
        final Condition c1 = ROOM.newCondition();
        final Condition c2 = ROOM.newCondition();

        new Thread(() -> {
            ROOM.lock();
            try {
                while (!r1) {
                    log.debug("t1 await");
                    try {
                        c1.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println("t1 run");
            } finally {
                ROOM.unlock();
            }
        }, "t1").start();
        new Thread(() -> {
            ROOM.lock();
            try {
                while (!r2) {
                    log.debug("t2 await");
                    try {
                        c2.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println("t2 run");
            } finally {
                ROOM.unlock();
            }
        }, "t2").start();
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        ROOM.lock();
        try {
            r1 = true;
            c2.signalAll();
            //c1.signal();
//            r2 = true;

        } finally {
            ROOM.unlock();
        }
        log.debug("the end!");
    }
}
